#include "server.h"
#include "connection.h"
#include <iostream>

WebSocketServer::WebSocketServer(boost::asio::io_context& io_context, uint16_t port)
:_ioc(io_context)
,_acceptor(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
    std::cout << "web socket server start on port " << port << std::endl;
}

void WebSocketServer::start_accept()
{
    auto con_ptr = std::make_shared<Connection>(_ioc);
    _acceptor.async_accept(con_ptr->socket(),
        [this, con_ptr](boost::system::error_code ec)
        {
            try 
            {
                if (ec)
                {
                    std::cout << "accept error: " << ec.message() << std::endl;
                    return;
                }
    
                con_ptr->async_accept();
                start_accept();
            } 
            catch (std::exception& e) 
            {
                std::cout << "start_accept exception: " << e.what() << std::endl;
            }
        });
}